<template>
  <div class="box">
    <h1>绘制跟随鼠标移动的方块</h1>

    <!-- 让创建的ref对象-box，和ref属性进行绑定 -->
    <div class="moveBox" ref="box">
      <div class="move" :style="{left:pos.x+'px',top:pos.y+'px'}"></div>
    </div>
  </div>
</template>

<script>
import {ref,reactive,onMounted,onBeforeUnmount} from "vue"
export default {
    setup(){
        //1.创建ref对象,这个时候没有值，导出给上面的模板使用
        let box =  ref(null);
        console.log(box);

        //5.定义位置的响应式数据
        let pos = reactive({x:0,y:0})

        function move(e){
               let x = e.clientX - box.value.offsetLeft;
               let y = e.clientY - box.value.offsetTop;

               if(x<=0){x=0}
               if(y<=0){y=0}
               if(x >= 450){ x = 450}
               if(y >= 450){ y = 450}

               //让元素随鼠标移动
               pos.x = x;
               pos.y = y;
            }

        //3.挂载完成后，就可以获取到页面的dom节点
        onMounted(()=>{
            console.log(box.value); //获取到对应的dom节点
            //4.给dom节点添加移动事件
            box.value.addEventListener("mousemove",move)
        });

        //6.组件销毁，事件就取消
        onBeforeUnmount(()=>{
            box.value.removeEventListener("mousemove",move)
        })
        //2.return
        return{
            box,
            pos
        }
    }
};
</script>

<style scoped>
  .moveBox{
    width: 500px;
    height: 500px;
    border: 2px solid red;
    margin: 0px auto;
    position: relative;
  }
  .move{
    width: 50px;
    height: 50px;
    background: teal;
    position: absolute;
  }
</style>